const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//创建补0函数
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//秒转播放时长对象
const formatAudio = second => {
  //天
  var day = Math.floor(second / (3600 * 24))
  // 小时位
  var hour = Math.floor((second - day * 3600 * 24) / 3600);
  // 分钟位
  var min = Math.floor((second - day * 3600 * 24 - hour * 3600) / 60);
  // 秒位
  var sec = (second - day * 3600 * 24 - hour * 3600 - min * 60); // equal to => var sec = second % 60;

  return {
    'day': day,
    'hour': formatNumber(hour),
    'min': formatNumber(min),
    'sec': formatNumber(sec)
  }
}

//播放时长转成秒（audioBackTime）
const timestr2sec = str => {
  if (!str) return '';
  let s = str.split(":");
  let len = s.length;
  let t = 0;
  for (let i in s) {
    t += parseInt(s[i]) * Math.pow(60, (len - i - 1));
  }
  console.log(t);
  return t
}


//秒转播放时长字符串（audioTime）
const sec2timestr = s => {
  let t = '';
  if (s > -1) {
    let min = Math.floor(s / 60);
    let sec = s % 60;
    if (min < 10) {
      t = "0";
    }
    t += min + ":";
    if (sec < 10) {
      t += "0";
    }
    t += sec.toFixed(0);
  }
  return t;
}

const reverseFormat = value => {
  var theTime = parseInt(value); // 秒
  var middle = 0; // 分
  var hour = 0; // 小时

  if (theTime > 59) {
    middle = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (middle > 59) {
      hour = parseInt(middle / 60);
      middle = parseInt(middle % 60);
    }
  }
  if (parseInt(hour) < 10) {
    hour = '0' + hour
  }
  if (parseInt(middle) < 10) {
    middle = '0' + middle
  }
  if (parseInt(theTime) < 10) {
    theTime = '0' + theTime
  }
  var result = hour + ":" + middle + ":" + theTime;

  return result;
}

//节流
const throttle = (fn, t = 1000) => {
  if (typeof fn !== 'function') throw new Error('第一个参数必须是方法')
  let _fn = fn
  let time = null
  let first = true
  return function () {
    let arg = arguments
    let _this = this
    if (first) {
      _fn.apply(_this, arg)
      first = false
      return
    }
    if (time) return
    time = setTimeout(function () {
      setTimeout(time)
      time = null
      _fn.apply(_this, arg)
    }, t)
  }
}

//防抖
const debounce = (fn, t, immediate = true) => {
  if (typeof fn !== 'function') throw new Error('第一个参数必须是方法')
  let _fn = fn;
  let timer;
  return function () {
    if (timer) clearTimeout(timer);
    if (immediate) {
      // 如果已经执行过，不再执行
      var callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, t)
      if (callNow) {
        _fn.apply(this, arguments)
      }
    } else {
      timer = setTimeout(() => {
        _fn.apply(this, arguments)
      }, t);
    }
  }
}

/**
 * 初始化类型判断方法
 * 在exp对象上新增isNull, isUndefined, isObject, isArray, isString, isNumber, isBoolean, isFunction, isRegExp
 * 可以通过Exp.isUndefined ...这些进行数据格式判断
 */
let exp = {};
let type = (o) => {
  let s = Object.prototype.toString.call(o)
  return s.match(/\[object (.*?)\]/)[1].toLowerCase()
};

['Null',
  'Undefined',
  'Object',
  'Array',
  'String',
  'Number',
  'Boolean',
  'Function',
  'RegExp'
].forEach(function (t) {
  exp['is' + t] = function (o) {
    return type(o) === t.toLowerCase()
  }
});


const isEmptyObject = obj => {
  if (!exp.isObject(obj)) throw TypeError('参数不是真正的object对象')
  return JSON.stringify(obj) === '{}'
}

//数组过滤空值
const ArrayNotEmpty = arr => {
  var result = [];
  arr.map(function (val, index) {
    //过滤规则为，不为空串、不为null、不为undefined，也可自行修改
    if (val !== "" && val != undefined) {
      result.push(val);
    }
  });
  return result;
}

const getParamsFromScan = e => {
  let opt = {};
  if (e.q) {
    //从网页进入小程序
    let news = decodeURIComponent(e.q).split("?");
    news = decodeURIComponent(news[1]).split("&");
    for (let i in news) {
      let tihuan = news[i].split("=");
      opt[tihuan[0]] = tihuan[1];
    }
  } else if (e.scene) {
    // 扫小程序菊花码
    let scene = decodeURIComponent(e.scene).split("&");
    for (let j in scene) {
      opt[scene[j].split('=')[0]] = unescape(scene[j].split('=')[1])
    }
  } else {
    opt = e
  }

  return opt;
}

let oldtime = '';

const preventclick = msc => { //防止重复点击
  if (oldtime == '') {
    oldtime = new Date().getTime();
    return true;
  } else {
    let newtime = new Date().getTime();
    if (newtime - oldtime > msc) {
      oldtime = new Date().getTime();
      return true;
    } else {
      return false;
    }
  }
}


/**
 * 身份证校验
 */
const checkIdcard = idCard => {
  if (idCard.slice(17, 18) == "x") {
    idCard = idCard.replace("x", "X");
  }
  idCard = idCard.toString();
  let city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外 "
  };
  let tip = "";
  let pass = true;

  if (!idCard ||
    !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
      idCard
    )
  ) {
    tip = "身份证号格式错误";
    pass = false;
  } else if (!city[idCard.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  } else {
    //18位身份证需要验证最后一位校验位
    if (idCard.length == 18) {
      idCard = idCard.split("");
      //∑(ai×Wi)(mod 11)
      //加权因子
      let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      let parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      let ai = 0;
      let wi = 0;
      for (let i = 0; i < 17; i++) {
        ai = idCard[i];
        wi = factor[i];
        sum += ai * wi;
      }
      let last = parity[sum % 11];
      if (parity[sum % 11] != idCard[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  let obj = {
    status: pass,
    msg: tip
  };
  if (!pass) {
    return obj;
  }
  return obj;
};

/**
 * 如果target(也就是obj1[key])存在，
 * 且是对象的话再去调用deepMerge，
 * 否则就是obj1[key]里面没这个对象，需要与obj2[key]合并
 */
const deepMerge = (obj1, obj2) => {
  let key;
  for (key in obj2) {
    obj1[key] = obj1[key] && obj1[key].toString() === "[object Object]" ?
      deepMerge(obj1[key], obj2[key]) : obj1[key] = obj2[key];
  }
  return obj1;
}

const isEmail = email => {
  const exp = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
  const mail = String(email)
  return exp.test(mail)
}
const wxuuid = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid
};
module.exports = {
  exp: exp,
  throttle: throttle,
  debounce: debounce,
  formatNumber: formatNumber,
  formatTime: formatTime,
  formatAudio: formatAudio,
  timestr2sec: timestr2sec,
  sec2timestr: sec2timestr,
  reverseFormat: reverseFormat,
  isEmptyObject: isEmptyObject,
  ArrayNotEmpty: ArrayNotEmpty,
  preventclick: preventclick,
  checkIdcard: checkIdcard,
  getParamsFromScan: getParamsFromScan,
  deepMerge: deepMerge,
  isEmail: isEmail,
  wxuuid:wxuuid
}